package com.hsogoo.ultraman.repository;

import java.util.List;
import java.util.Properties;

import com.google.common.collect.Lists;
import com.hsogoo.ultraman.container.ConfigContainer;
import com.hsogoo.ultraman.listener.RemoteConfigChangeListener;
import com.hsogoo.ultraman.listener.RepositoryChangeListener;
import com.hsogoo.ultraman.monitor.ConfigChangeMonitor;

import lombok.extern.slf4j.Slf4j;

/**
 * Created by za-huangsaigang on 2018/9/13.
 */
@Slf4j
public abstract class AbstractConfigRepository implements ConfigRepository {

    private List<RepositoryChangeListener> listeners = Lists.newCopyOnWriteArrayList();

    @Override
    public void addChangeListener(RepositoryChangeListener listener) {
        if (!listeners.contains(listener)) {
            listeners.add(listener);
        }
    }

    @Override
    public void removeChangeListener(RepositoryChangeListener listener) {
        listeners.remove(listener);
    }

    protected void fireRepositoryChange(String namespace, Properties newProperties) {
        for (RepositoryChangeListener listener : listeners) {
            try {
                listener.onRepositoryChange(namespace, newProperties);
            } catch (Throwable ex) {
                log.error("Failed to fire repository change method {}",listener.getClass(), ex);
            }
        }
    }
}
